#include "cmd_input.h"

int get_cmd_input(int argc, char* argv[], size_t *width, size_t*height) {
    int opt;
    *width = DEFAULT_WIDTH;
    *height = DEFAULT_HEIGHT;

    while ((opt = getopt(argc, argv, "w:h:")) != -1) {
        switch (opt) {
            case 'w': {
                char* endptr;
                long tmp = strtol(optarg, &endptr, 10);
                if (endptr == optarg || *endptr != '\0') {
                    fprintf(stderr, "Error: width '%s' is not a valid number\n", optarg);
                    return EXIT_FAILURE;
                }
                if (tmp <= 0) {
                    fprintf(stderr, "Error: width must be a positive integer (input value: %ld)\n", tmp);
                    return EXIT_FAILURE;
                }
                *width = (size_t)tmp;
                break;
            }

            case 'h': {
                char* endptr;
                long tmp = strtol(optarg, &endptr, 10);
                if (endptr == optarg || *endptr != '\0') {
                    fprintf(stderr, "Error: height '%s' is not a valid integer\n", optarg);
                    return EXIT_FAILURE;
                }
                if (tmp <= 0) {
                    fprintf(stderr, "Error: height must be a positive integer (input value: %ld)\n", tmp);
                    return EXIT_FAILURE;
                }
                *height = (size_t)tmp;
                break;
            }

            case '?':
                if (optopt == 'w' || optopt == 'h') {
                    fprintf(stderr, "Error: option -%c requires an argument\n", optopt);
                } else {
                    fprintf(stderr, "Error: unknown option '-%c'\n", optopt);
                }
                return EXIT_FAILURE;

            default:
                fprintf(stderr, "Usage: %s [-w width] [-h height]\n", argv[0]);
                return EXIT_FAILURE;
        }
    }

    // Output the final parameter values used
    printf("Width: %zu\n", *width);
    printf("Height: %zu\n", *height);

    // Handle other non-option arguments
    if (optind < argc) {
        printf("Non-option arguments: ");
        for (int i = optind; i < argc; i++) {
            printf("%s ", argv[i]);
        }
        printf("\n");
    }

    return EXIT_SUCCESS;
}
